package com.ztjc.day04_internetimage;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 网络图片查看器
 */
public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";
    private ImageView iv_image;
    private String path = "http://girlatlas.b0.upaiyun.com/3215/20140626/152521667e57aa1683ec.jpg!mid";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv_image = (ImageView) findViewById(R.id.iv_image);

        // 判断本地是否存在缓存的图片，如果存在直接拿来显示，如果不存在去网上下载
        File file = new File(Environment.getExternalStorageDirectory(), getFileName(path));
        if (file.exists()) {
            iv_image.setImageBitmap(BitmapFactory.decodeFile(file.getPath()));
            Log.i(TAG, "本地缓存的");
        } else {
            new DownLoadTask().execute(path);
            Log.i(TAG, "网络下载的");
        }
    }

    class DownLoadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File file = null;
                HttpURLConnection connection = null;
                FileOutputStream fileOutputStream = null;
                try {
                    URL url = new URL(params[0]);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    if (connection.getResponseCode() == 200) {
                        file = new File(Environment.getExternalStorageDirectory(), getFileName(params[0]));
                        fileOutputStream = new FileOutputStream(file);
                        byte[] b = new byte[1024];
                        int len = 0;
                        InputStream inputStream = connection.getInputStream();
                        while ((len = inputStream.read(b)) != -1) {
                            fileOutputStream.write(b, 0, len);
                        }
                    }
                    if (file != null) {
                        return file.getPath();
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fileOutputStream != null) {
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            iv_image.setImageBitmap(BitmapFactory.decodeFile(s));
        }
    }

    /**
     * 获取文件名称
     *
     * @param param
     * @return
     */
    private String getFileName(String param) {
        return param.substring(param.lastIndexOf("/") + 1);
    }
}
